#!/usr/bin/env python
# coding: utf-8

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
#from django.views.generic import DetailView, ListView, CreateView, UpdateView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.core.context_processors import csrf
from django.contrib import messages
from datetime import datetime
from django.db.models import Q
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.utils.html import urlize

from main.views import get_default_context
from main.authfuncs import get_user_profile, auth_user_required
from forms import TopicForm
from forms import UnBlogEditForm
from forms import UnBlogAddForm
from models import UnBlog, Topic

def paginate(request, objects):
    paginator = Paginator(objects, 10)
    try:
        page = int(request.GET.get('p', '1') )
    except ValueError:
        page = 1
    try:
        obj_page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        obj_page = paginator.page(paginator.num_pages)
    return obj_page

def unblog(request, *args, **kwargs):
    # assert False
    #if request.method == 'POST': assert False
    topic_id = kwargs.get('topic_id', None)
    post_id = kwargs.get('post_id', None)
    topic = get_object_or_404(Topic, id = topic_id) if topic_id else None
    topic_list = Topic.objects.filter( Q(public = False, user = request.user if request.user.is_authenticated() else 0) | Q(public = True) )[:10]

    allowed = False
    if topic and request.user.is_authenticated():
        if request.user.is_staff: allowed = True
        if (topic.guest_ok and topic.public) or topic.user == request.user: allowed = True

    if allowed and topic and request.POST.get('text', None):
        add_form = UnBlogAddForm(request.POST)
        if add_form.is_valid():
            data = add_form.cleaned_data
            post = UnBlog(user = request.user, topic_id = topic_id, text = data['text'], datetime = datetime.now())
            post.save()
            messages.info(request, u"Записка записана")
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))
    add_form = UnBlogAddForm()

    request_result = process_unblog_requests(request, topic)
    if request_result: return request_result

    c = get_default_context(request)

    c['topic_id'] = topic_id
    c['topic'] = topic
    c['topic_list'] = topic_list
    c['allowed'] = allowed
    c['add_form'] = add_form
    c['unblog_edit_form'] = UnBlogEditForm().as_p()

    c['add_topic_form'] = TopicForm() if request.user.is_authenticated() else None
    c['edit_topic_form'] = TopicForm() if topic and request.user.is_authenticated() and topic.user == request.user else None

    if not topic: unblogs = UnBlog.objects.filter(topic__public = True)
    elif topic and (topic.public or topic.user == request.user) or (not topic.public and topic.guest_ok): 
        if not post_id: unblogs = UnBlog.objects.filter(topic = topic_id)
        else:
            unblogs = [get_object_or_404(UnBlog, topic = topic_id, id = post_id) ]

    else: unblogs = []
    pages = paginate(request, unblogs)
    unblogs = pages.object_list
    result = []
    #for one in unblogs:
    #    profile = get_user_profile(user = one.user)
    #    result.append({ 'username': profile, 
    #                    'photo': profile.photo, 
    #                    'datetime': one.datetime,
    #                    'text': one.text,
    #                    'brief': one.__unicode__(),
    #                    'permalink': one.get_permalink()
    #                    })
    c['pages'] = pages
    c['unblogs'] = unblogs
    return render_to_response('unblog.html', c)


def unblog_topic_list(request, *args, **kwargs):

    c = get_default_context(request)
    topics = Topic.objects.filter(public = True)
    c['topic_list'] = topics
    return render_to_response('unblog_topic_list.html', c)


# @auth_user_required
# def unblog_add(request, *args, **kwargs):
#     from forms import UnBlogAddForm

#     c = get_default_context(request)

#     if request.method == 'POST':
#         form =contacts UnBlogAddForm(request.POST)
#         if form.is_valid():
#             data = form.cleaned_data
#             post = UnBlog(user = request.user, text = data['text'], datetime = datetime.now())
#             post.save()
#             messages.info(request, u"Записка записана")
#             return HttpResponseRedirect(reverse('unblog'))
#     else:
#         form = UnBlogAddForm()
    
#     c['form'] = form

#     return render_to_response('forms/unblog_add_form.html', c)

def process_unblog_requests(request, topic):

    if not request.user.is_authenticated(): return None

    if request.POST.get('del_id', None):
        try:
            del_id = int(request.POST.get('del_id'))
            post = UnBlog.objects.get(id = del_id)
            if post.user == request.user or request.user.is_staff:
                post.delete()
                messages.info(request, u"Записка удалена")
            else:
                messages.info(request, u"Не свое - не трогай!")
        except:
            messages.info(request, u"Записка не удалена...")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))
    
    if request.POST.get('delete_topic', None):
        try:
            del_id = int(request.POST.get('del_id'))
            post = UnBlog.objects.get(id = del_id)
            if post.user == request.user or request.user.is_staff:
                post.delete()
                messages.info(request, u"Записка удалена")
            else:
                messages.info(request, u"Не свое - не трогай!")
        except:
            messages.info(request, u"Записка не удалена...")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))

    if request.POST.get('edit_id', None):
        edit_id = None
        try:
            edit_id = int(request.POST.get('edit_id', None))
        except:
            messages.info(request, u"Что-то не так...")
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))
        if edit_id and request.POST.get('blog_edit_area', None):
            edit_form = UnBlogEditForm(request.POST)
            if not edit_form.is_valid(): 
                messages.info(request, u"Что-то отправилось не правильно...")
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))
            text = edit_form.cleaned_data['blog_edit_area']
            try:
                post = UnBlog.objects.get(id = edit_id)
                if post.user == request.user or request.user.is_staff:
                    post.text = text
                    post.corrected = datetime.now()
                    post.save()
                    messages.info(request, u"Записка исправлена")
                else:
                    messages.info(request, u"Не свое - не трогай!")
            except:
                messages.info(request, u"Записка не сохранилась...")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))

    if request.POST.get('topic_title', None) and not request.POST.get('topic_edit', None):
        create_form = TopicForm(request.POST)
        if create_form.is_valid():
            new_topic = Topic(title = create_form.cleaned_data['topic_title'], user = request.user)
            new_topic.save()
            return HttpResponseRedirect(reverse('unblog_topic', kwargs = {'topic_id': new_topic.id}))
        else:
            messages.info(request, u"Не получилось добавить тему...")

    if topic:
        # Обрабатываем добавление топика
        # редактирование топика
        if request.POST.get('topic_title', None) and request.POST.get('topic_edit', None):
            edit_form = TopicForm(request.POST)
            if not edit_form.is_valid(): 
                messages.info(request, u"Что-то отправилось не правильно...")
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/blog/'))
                try:
                    if topic.user == request.user or request.user.is_staff:
                        topic.title = edit_form.cleaned_data['topic_title']
                        topic.save()
                        messages.info(request, u"Тема исправлена")
                        return HttpResponseRedirect(reverse('unblog_topic', kwargs = {'topic_id': topic.id}))
                    else:
                        messages.info(request, u"Не свое - не трогай!")
                except:
                    messages.info(request, u"Тема не сохранилась...")
        # удаление топика
        if request.POST.get('delete_current', False):
            if topic.user == request.user:
                topic.delete()
                messages.info(request, u"Тема удалена")
            else:
                messages.info(request, u"Не свое - не трогай!")
            return HttpResponseRedirect(reverse('unblog'))
